<template>
  <Dialog
    class="slim-dialog"
    :title="t('studentPatent.view.title')"
    v-model="dialogVisible"
    width="950"
  >
    <template
      v-if="
        !edit &&
        type === 'edit' &&
        (formData.reviewStatus === '草稿' ||
          formData.reviewStatus === '已撤回' ||
          formData.reviewStatus === '已拒绝')
      "
    >
      <el-button class="mb-[16px]" type="primary" plain @click="handleEdit" :disabled="formLoading">
        <Icon icon="ep:edit" />
        {{ t('studentPatent.view.clickEdit') }}
      </el-button>
    </template>
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-position="top"
      label-width="120px"
      @submit.prevent
    >
      <el-descriptions v-loading="formLoading" :column="1" border label-width="230">
        <el-descriptions-item
          label-class-name="is--asterisk"
          :label="t('studentPatent.fields.patentName')"
        >
          <el-form-item prop="patentName">
            <EditInput
              v-model="formData.patentName"
              :placeholder="t('common.inputTextPlaceholder') + t('studentPatent.fields.patentName')"
              :maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item
          label-class-name="is--asterisk"
          :label="t('studentPatent.fields.attachment')"
        >
          <el-form-item prop="attachment" style="width: 100%">
            <IMRUpload
              v-model="formData.attachment"
              :file-type="['pdf']"
              :file-size="3"
              :limit="1"
              :disabled="!edit"
            />
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item
          label-class-name="is--asterisk"
          :label="t('studentPatent.fields.patentType')"
        >
          <el-form-item prop="patentType">
            <EditDict
              :dict-type="DICT_TYPE.RESEARCH_PATENT_TYPE"
              v-model="formData.patentType"
              :placeholder="
                t('common.selectTextPlaceholder') + t('studentPatent.fields.patentType')
              "
            />
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item
          label-class-name="is--asterisk"
          :label="t('studentPatent.fields.patentStatus')"
        >
          <el-form-item prop="patentStatus">
            <EditDict
              :dict-type="DICT_TYPE.RESEARCH_PATENT_STATUS"
              v-model="formData.patentStatus"
              :placeholder="
                t('common.selectTextPlaceholder') + t('studentPatent.fields.patentStatus')
              "
            />
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item
          v-if="formData.patentStatus === '已公开'"
          label-class-name="is--asterisk"
          :label="t('studentPatent.fields.publishNumber')"
        >
          <el-form-item prop="publishNumber">
            <EditInput
              v-model="formData.publishNumber"
              :placeholder="
                t('common.inputTextPlaceholder') + t('studentPatent.fields.publishNumber')
              "
              :maxlength="50"
            />
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item
          v-if="formData.patentStatus === '已公开'"
          label-class-name="is--asterisk"
          :label="t('studentPatent.fields.publishTime')"
        >
          <el-form-item prop="publishTime">
            <EditDate
              v-model="formData.publishTime"
              :placeholder="
                t('common.selectTextPlaceholder') + t('studentPatent.fields.publishTime')
              "
            />
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item
          v-if="formData.patentStatus === '已授权'"
          label-class-name="is--asterisk"
          :label="t('studentPatent.fields.patentNumber')"
        >
          <el-form-item prop="patentNumber">
            <EditInput
              v-model="formData.patentNumber"
              :placeholder="
                t('common.inputTextPlaceholder') + t('studentPatent.fields.patentNumber')
              "
              :maxlength="50"
            />
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item
          v-if="formData.patentStatus === '已授权'"
          label-class-name="is--asterisk"
          :label="t('studentPatent.fields.patentTime')"
        >
          <el-form-item prop="patentTime">
            <EditDate
              v-model="formData.patentTime"
              :placeholder="
                t('common.selectTextPlaceholder') + t('studentPatent.fields.patentTime')
              "
            />
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item
          label-class-name="is--asterisk"
          :label="t('studentPatent.fields.personalRanking')"
        >
          <el-form-item key="personalRanking" prop="personalRanking">
            <EditDict
              :dict-type="DICT_TYPE.RESEARCH_PATENT_PERSONAL_RANK"
              v-model="formData.personalRanking"
              :placeholder="
                t('common.selectTextPlaceholder') + t('studentPatent.fields.personalRanking')
              "
            />
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item
          label-class-name="is--asterisk"
          :label="t('studentPatent.fields.casRanking')"
        >
          <el-form-item key="casRanking" prop="casRanking">
            <EditDict
              :dict-type="DICT_TYPE.RESEARCH_PATENT_USTC_RANK"
              v-model="formData.casRanking"
              :placeholder="
                t('common.selectTextPlaceholder') + t('studentPatent.fields.casRanking')
              "
            />
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item
          label-class-name="is--asterisk"
          :label="t('studentPatent.fields.imrRanking')"
        >
          <el-form-item key="imrRanking" prop="imrRanking">
            <EditDict
              :dict-type="DICT_TYPE.RESEARCH_PATENT_IMR_RANK"
              v-model="formData.imrRanking"
              :placeholder="
                t('common.selectTextPlaceholder') + t('studentPatent.fields.imrRanking')
              "
            />
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item :label="t('studentPatent.fields.remark')">
          <el-form-item prop="remark">
            <EditInput
              v-model="formData.remark"
              type="textarea"
              :rows="2"
              :maxlength="200"
              show-word-limit
              :placeholder="t('common.inputTextPlaceholder') + t('studentPatent.fields.remark')"
            />
          </el-form-item>
        </el-descriptions-item>
        <template v-if="type === 'edit'">
          <el-descriptions-item :label="t('studentPatent.fields.reviewStatus')">
            <el-tag v-if="formData.reviewStatus" type="primary"
              >{{ formData.reviewStatus }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item :label="t('studentPatent.fields.reviewTime')">
            {{ formatDate(formData.reviewTime) }}
          </el-descriptions-item>
        </template>
      </el-descriptions>
    </el-form>

    <template v-if="edit" #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading"
        >{{ t('common.ok') }}
      </el-button>
      <el-button @click="handleCancelClick">{{ t('common.cancel') }}</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { StudentPatentApi, StudentPatentVO } from '@/api/core/studentpatent'
import { DICT_TYPE } from '@/utils/dict'
import { formatDate } from '@/utils/formatTime'
import EditDate from '@/components/EditViewInput/EditDate.vue'
import IMRUpload from '@/components/IMRUpload/index.vue'
import EditDict from '@/components/EditViewInput/EditDict.vue'
import EditInput from '@/components/EditViewInput/EditInput.vue'
import { FormInstance } from 'element-plus'
import _ from 'lodash-es'

/** 专利 表单 */
defineOptions({ name: 'StudentPatentForm' })

const edit = ref(false)
provide('editMode', edit)

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref<Partial<StudentPatentVO>>({})
const type = ref('edit')
const formRef = ref<FormInstance>()

const formRules = reactive({
  // 专利名称
  patentName: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('studentPatent.fields.patentName'),
      trigger: 'blur'
    }
  ],
  // 专利类型
  patentType: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('studentPatent.fields.patentType'),
      trigger: 'change'
    }
  ],
  // 附件
  attachment: [
    {
      required: true,
      message: t('common.uploadText') + t('studentPatent.fields.attachment'),
      trigger: 'blur'
    }
  ],
  // 专利状态
  patentStatus: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('studentPatent.fields.patentStatus'),
      trigger: 'change'
    }
  ],
  // 专利公开号
  publishNumber: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('studentPatent.fields.publishNumber'),
      trigger: 'blur'
    }
  ],
  // 公开时间
  publishTime: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('studentPatent.fields.publishTime'),
      trigger: 'change'
    }
  ],
  // 专利授权号
  patentNumber: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('studentPatent.fields.patentNumber'),
      trigger: 'blur'
    }
  ],
  // 授权时间
  patentTime: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('studentPatent.fields.patentTime'),
      trigger: 'change'
    }
  ],
  // 个人排名
  personalRanking: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('studentPatent.fields.personalRanking'),
      trigger: 'change'
    }
  ],
  // CAS 排名
  casRanking: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('studentPatent.fields.casRanking'),
      trigger: 'change'
    }
  ],
  // IMR 排名
  imrRanking: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('studentPatent.fields.imrRanking'),
      trigger: 'change'
    }
  ]
})

const dataId = ref('')
/** 打开弹窗 */
const open = async (id?: string) => {
  formData.value = {}
  if (id) {
    dataId.value = id
    type.value = 'edit'
    // 修改
    edit.value = false
    dialogVisible.value = true
    formLoading.value = true
    try {
      formData.value = await StudentPatentApi.getStudentPatent(id)
      if (formData.value && !formData.value?.attachment) {
        formData.value.attachment = '[]'
      }
    } finally {
      formLoading.value = false
    }
  } else {
    // 新增
    type.value = 'new'
    edit.value = true
    dialogVisible.value = true
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  try {
    await formRef.value?.validate()
  } catch {
    return
  }
  if (!formData.value.attachment || formData.value.attachment === '[]') {
    message.error(t('common.uploadText') + t('studentPatent.fields.attachment'))
    return
  }
  if (type.value === 'edit') {
    // 提交请求
    formLoading.value = true
    try {
      const data = formData.value as unknown as StudentPatentVO
      await StudentPatentApi.updateStudentPatent(data)
      message.success(t('common.updateSuccess'))
      dialogVisible.value = false
      // 发送操作成功的事件
      emit('success')
    } finally {
      formLoading.value = false
    }
  } else {
    // 新增
    formLoading.value = true
    try {
      const data = formData.value as unknown as StudentPatentVO
      await StudentPatentApi.createStudentPatent(data)
      message.success(t('common.createSuccess'))
      dialogVisible.value = false
      // 发送操作成功的事件
      emit('success')
    } finally {
      formLoading.value = false
    }
  }
}

const backData = ref<Partial<StudentPatentVO>>({})

const handleEdit = () => {
  if (type.value === 'edit') {
    backData.value = _.cloneDeep(formData.value)
    edit.value = true
  }
}

const handleCancelClick = () => {
  if (type.value === 'edit') {
    edit.value = false
    formData.value = _.cloneDeep(backData.value)
    backData.value = {}
  } else {
    dialogVisible.value = false
  }
}
</script>

<style lang="scss" scoped>
:deep(.el-form-item) {
  margin-bottom: 0;
}

:deep(.is--asterisk) {
  &:after {
    content: '*';
    margin-left: 4px;
    color: var(--el-color-primary);
  }
}

:deep(.el-form-item__error) {
  top: 80%;
}
</style>
